package com.gxa.modules.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gxa.component.jwt.JwtResult;
import com.gxa.component.jwt.JwtUtil;
import com.gxa.component.jwt.JwtUtils;
import com.gxa.component.jwt.SysUser;
import io.jsonwebtoken.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.SignatureException;
import java.util.HashMap;
import java.util.Map;

public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(request.getMethod().toUpperCase().equals("OPTIONS")){
            return true; // 通过所有OPTION请求
        } else {
//            RedisTemplate redisTemplate=new RedisTemplate();

            String token = request.getHeader("token"); // 获取请求头中的token

            //根据token获取用户名
            Claims claims = JwtUtils.parseJWT(token);
            String subject = claims.getSubject();
            System.out.println(subject);
            System.out.println(redisTemplate);

//            redisTemplate.opsForValue().get(subject);
//            System.out.println(redisTemplate.opsForValue().get(subject));

            JwtResult verify = JwtUtils.validateToken(token);
            if (verify.isSuccess()) {
                return true; // 通过验证
            } else {
//                    map.put("msg", "不支持的签名");
                return false; // 未通过验证
            }
        }
    }
}